<?php

namespace tmcore\services\addons\module;

use think\Exception;
use think\facade\Config;
use think\facade\Db;
use tmcore\services\addons\BaseService;
use think\db\exception\PDOException;

class Sql extends BaseService
{

    /**
     * 执行sql
     * @param string $sql_file
     * @return bool
     * @throws Exception
     */
    public function executeSql(string $sql_file): bool
    {
        $tempLine = '';
        if (is_file($sql_file)) {
            $lines = file($sql_file);
            Db::startTrans();
            try {
                foreach ($lines as $line) {
                    if (str_starts_with($line, '--') || $line == '' || str_starts_with($line, '/*')) {
                        continue;
                    }

                    $tempLine .= $line;
                    if (str_ends_with(trim($line), ';')) {
                        $tempLine = str_ireplace('{{PREFIX}}', Config::get('database.connections.mysql.prefix'), $tempLine);
                        $tempLine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $tempLine);
                        Db::execute($tempLine);
                        $tempLine = '';
                    }
                }
                Db::commit();
                return true;
            } catch ( PDOException $e ) {
                Db::rollback();
                throw new Exception($e->getMessage());
            }
        }

        return true;
    }
}